﻿using BW.Mes.WinForms.Production.ProductionCommon;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.Production.ProductionCommon.MainForm;

namespace BW.Mes.WinForms.Production.ProductionState
{
    public partial class ProduceTrueForm : DevExpress.XtraEditors.XtraForm
    {
        public ProduceTrueForm()
        {
            InitializeComponent();

            InitProductionTypeData();

            InitGridColumns();

            // 添加这行代码
            this.gridView1.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            // 绑定查询按钮事件
            this.simpleButton1.Click += ShowTrue_Click;
        }
        /// <summary>
        /// 设置网格列绑定
        /// </summary>
        private void InitGridColumns()
        {
            // 绑定数据列到实体类属性
            this.Type.FieldName = "ProductionType";
            this.Code.FieldName = "ProductionCode";
            this.Line.FieldName = "Process";
            this.date.FieldName = "ProductionDateTime";
            // 设置日期列的显示格式
            this.date.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            this.date.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;


        }


        /// <summary>
        /// 加载界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void True_Load(object sender, EventArgs e)
        {
            // 初始化列配置
            InitGridColumns();

            await LoadDate();

            // 在窗体加载完成后，确保列的顺序正确
            this.gridView1.BeginSort();
            try
            {
                // 重新设置所有列的VisibleIndex
                this.Ids.VisibleIndex = 0;
                this.Type.VisibleIndex = 1;
                this.Code.VisibleIndex = 2;
                this.Line.VisibleIndex = 3;
                this.date.VisibleIndex = 4;
                this.option.VisibleIndex = 5; // 确保是最后一列

                // 确保操作列可编辑
                this.option.OptionsColumn.AllowEdit = true;
                this.option.OptionsColumn.ReadOnly = false;
            }
            finally
            {
                this.gridView1.EndSort();
            }
        }

        /// <summary>
        /// 查询的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowTrue_Click(object sender, EventArgs e)
        {
            // 获取查询条件
            string productionType = this.ProductionType.EditValue?.ToString();
            string productionCode = this.textEdit2.Text.Trim();
            string process = this.textEdit3.Text.Trim();
            // 获取创建时间
            DateTime? dateStr = this.dateEdit1.EditValue as DateTime?;

            // 验证必填项
            if (string.IsNullOrEmpty(productionType))
            {
                XtraMessageBox.Show("请选择产品类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.ProductionType.Focus();
                return;
            }

            if (string.IsNullOrEmpty(productionCode))
            {
                XtraMessageBox.Show("请输入编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.textEdit2.Focus();
                return;
            }

            // 执行查询
            LoadDate(productionType, productionCode, process, dateStr);
        }

        /// <summary>
        /// 初始化产品类型(查询)
        /// </summary>
        private void InitProductionTypeData()
        {
            // 创建只有一个字段的数据表
            DataTable dt = new DataTable();
            dt.Columns.Add("ProductType");

            // 添加数据
            dt.Rows.Add("工单");
            dt.Rows.Add("产品");
            dt.Rows.Add("主数据");

            // 设置数据源，只使用一个字段
            this.ProductionType.Properties.DataSource = dt;
            this.ProductionType.Properties.DisplayMember = "ProductType";
            this.ProductionType.Properties.ValueMember = "ProductType";

            // 设置下拉列表显示的列
            this.gridLookUpEdit1View.Columns.Clear();
            this.gridLookUpEdit1View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
            {
                FieldName = "ProductType",
                Caption = "类型",
                Visible = true,
                VisibleIndex = 0
            });
        }

        /// <summary>
        /// 查询的业务逻辑
        /// </summary>
        public async Task LoadDate(string productionType = null, string productionCode = null, string process = null, DateTime? dateStr = null)
        {

            // 构建查询参数
            var queryParams = new Dictionary<string, string>();

            // 仅当参数有值时添加到查询参数中
            if (!string.IsNullOrEmpty(productionType))
                queryParams.Add("ProductionType", productionType);

            if (!string.IsNullOrEmpty(productionCode))
                queryParams.Add("ProductionCode", productionCode);

            if (!string.IsNullOrEmpty(process))
                queryParams.Add("Process", process);

            if (dateStr.HasValue)
                queryParams.Add("ProductionDateTime", dateStr.Value.ToString("yyyy-MM-dd"));

            // 构建查询baseUrl
            string baseUrl = ProduceConst.PRODUCE_TRUE;
            if (queryParams.Count > 0)
            {
                baseUrl += "?" + string.Join("&", queryParams.Select(p => $"{p.Key}={Uri.EscapeDataString(p.Value)}"));
            }


            //请求接口
            var result = await ProduceHttpClientHelper.RequestUrl(ProduceRequestType.get, baseUrl);
            //反序列化
            var showTrue = JsonConvert.DeserializeObject<ProduceApiResult<ProductionState>>(result);

            // 无论成功与否，先清空现有数据源
            this.gridControl1.DataSource = null;
            this.gridView1.RefreshData();

            if (showTrue.Success == true && showTrue.Data != null)
            {
                // 确保数据是列表类型
                var dataList = showTrue.Data as IEnumerable<ProductionState>;
                if (dataList == null)
                {
                    // 如果不是列表，可能是单个对象，转换为列表
                    if (showTrue.Data is ProductionState singleItem)
                    {
                        dataList = new List<ProductionState> { singleItem };
                    }
                    else
                    {

                        XtraMessageBox.Show("未查询到符合条件的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 数据为null，创建空列表
                        dataList = new List<ProductionState>();

                    }
                }
                // 为每个数据项设置option属性
                var list = dataList.ToList();

                this.gridControl1.DataSource = dataList;
                // 刷新网格视图
                this.gridView1.RefreshData();



            }
        }

        /// <summary>
        /// 删除产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelTrue_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前行索引
            int rowHandle = this.gridView1.FocusedRowHandle;
            if (rowHandle < 0)
            {
                XtraMessageBox.Show("请选择要删除的记录", "提示");
                return;
            }
            // 获取当前行的ID
            var idValue = this.gridView1.GetRowCellValue(rowHandle, "Id");
            long id = Convert.ToInt64(idValue);

            // 确认删除
            DialogResult result = XtraMessageBox.Show("确定要删除此记录吗？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                // 执行删除操作
                DeleteRecord(id);
            }
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        private async void DeleteRecord(long id)
        {
            // 构建删除API URL，传递ID参数
            string delUrl = $"{ProduceConst.Del_TRUE}/{id}";

            // 发送删除请求
            var responseJson = await ProduceHttpClientHelper.RequestUrl(ProduceRequestType.put, delUrl);

            // 检查响应是否为空
            if (string.IsNullOrEmpty(responseJson))
            {
                XtraMessageBox.Show("删除失败，服务器未返回数据", "错误");
                return;
            }

            // 反序列化响应
            var delResponse = JsonConvert.DeserializeObject<ProduceApiResult<bool>>(responseJson);

            if (delResponse != null && delResponse.Success)
            {
                XtraMessageBox.Show("删除成功", "提示");

                // 立即刷新数据，不要等待消息框关闭
                Application.DoEvents();

                await LoadDate();
            }
            else
            {
                string errorMsg = delResponse?.Message ?? "未知错误";
                XtraMessageBox.Show($"删除失败: {errorMsg}", "错误");
            }

        }
        /// <summary>
        /// 锁定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Lock_Click(object sender, EventArgs e)
        {

            // 创建ID列表，存储选中的记录ID
            List<long> selectedIds = new List<long>();

            // 遍历gridView1中的所有行
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                // 获取当前行的Ids值
                bool isSelected = Convert.ToBoolean(gridView1.GetRowCellValue(i, "Ids"));

                // 如果该行被选中
                if (isSelected)
                {
                    // 获取该行的Id值并添加到列表中
                    long id = Convert.ToInt64(gridView1.GetRowCellValue(i, "Id"));
                    selectedIds.Add(id);
                }
            }

            // 检查是否有选中的记录
            if (selectedIds.Count == 0)
            {
                XtraMessageBox.Show("请至少选择一条记录进行锁定", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var lockform = new ProduceLockForm(selectedIds);
            lockform.ShowDialog();

            
            await LoadDate();
        }


        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Reset_Click(object sender, EventArgs e)
        {
            // 清空所有查询条件
            this.ProductionType.EditValue = null;  // 清空产品类型
            this.textEdit2.Text = string.Empty;    // 清空编码
            this.textEdit3.Text = string.Empty;    // 清空工序
            this.dateEdit1.EditValue = null;       // 清空日期

            // 显示提示信息
            XtraMessageBox.Show("已重置所有查询条件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // 重新加载数据（不带任何查询条件）
            await LoadDate();
        }


        /// <summary>
        /// 实体类
        /// </summary>
        public class ProductionState
        {
            public bool Ids { get; set; }

            public string ProductionType { get; set; }
            public string ProductionCode { get; set; }
            public string Process { get; set; }
            public DateTime ProductionDateTime { get; set; }
            public bool ProduceState { get; set; }
            public string ProductionDesc { get; set; }
            public long Id { get; set; }
            public bool IsDeleted { get; set; }
            public DateTime CreatedAt { get; set; }
            public string CreatedBy { get; set; }

            public string option { get; set; }
        }
    }
}